package com.lushuan.springboot_lushuan.service;

import com.lushuan.springboot_lushuan.pojo.User;
import com.lushuan.springboot_lushuan.pojo.dto.UserDTO;
import com.lushuan.springboot_lushuan.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements IUserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public User add(UserDTO userDto) {
        User user = new User();
        // dto 对象转 pojo 对象
        BeanUtils.copyProperties(userDto,user);
        return userRepository.save(user);  // 可以返回也可以不返回

    }

    @Override
    public User getUser(Integer userId) {
        return userRepository.findById(userId).orElseThrow(() -> {
            throw new IllegalArgumentException("用户不存在，参数异常");
        });
    }

    @Override
    public User editUser(UserDTO userDto) {
        User user = new User();
        // dto 对象转 pojo 对象
        BeanUtils.copyProperties(userDto,user);
        return userRepository.save(user);
    }

    @Override
    public void deleteUser(Integer userId) {
        userRepository.deleteById(userId);
    }
}
